package com.fognl.core.net.handler.request;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import com.fognl.core.net.handler.AbstractRequest;
import com.fognl.core.net.handler.Request;
import com.fognl.core.net.handler.WorkerException;

/** read a file line-by-line, deliver to a listener as lines are read. */
public class LinewiseFileReadRequest extends AbstractRequest
{
	private File file;
	
	public LinewiseFileReadRequest(File file)
	{
		super();
		this.file = file;
	}
	
	public File getFile() { return file; }
	
	public Worker getWorker()
	{
		return new Request.Worker() {
			private List<String> lines;
			
			public Object getData()
			{
				return lines;
			}
			
			public void work(Request.Worker.Listener listener) throws WorkerException
			{
				try {
					lines = new ArrayList<String>();
					
					BufferedReader reader = new BufferedReader(new FileReader(file));
					try {
						String line;
						while((line = reader.readLine()) != null)
						{
							Thread.yield();
							if(!listener.okToContinue(this))
								break;
							
							listener.onData(line);
							lines.add(line);
						}
					}
					finally {
						reader.close();
					}
				}
				catch(Exception ex)
				{
					throw new WorkerException(ex.getMessage(), ex);
				}
			}
		};
	}
}
